using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Management.Automation;
using System.Management.Automation.Host;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Threading;
using System.Xml;
using PoshWpf.Utility;
using System.Collections;

namespace PoshWpf.Commands
{
   [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")]
   [Cmdlet(VerbsCommon.Show, "UI", SupportsShouldProcess = false, ConfirmImpact = ConfirmImpact.None, DefaultParameterSetName = "DataTemplate")]
   public class ShowUICommand : ScriptBlockBase
   {
      #region Parameters
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays"), Parameter(Position = 0, Mandatory = false, ValueFromPipeline = true, HelpMessage = "The Content for the WPF window ...")]
      public ScriptBlock[] Content { get; set; }

      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays"), Parameter(Position = 1, Mandatory = false, ValueFromRemainingArguments = true)]
      [Alias("Args", "Params")]
      public Object[] Parameters { get; set; }

      [Parameter(Mandatory = false, ValueFromPipeline = true)]
      [Alias("Threaded")]
      public SwitchParameter Async { get; set; }

      // TODO!
      [Parameter(Position = 10, Mandatory = true, ValueFromPipeline = false, ParameterSetName = "FileTemplate", HelpMessage = "XAML template file")]
      public FileInfo FileTemplate { get; set; }

      // we're accepting  XmlDocument because that's what PowerShell has.
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1059:MembersShouldNotExposeCertainConcreteTypes", MessageId = "System.Xml.XmlNode"),
       Parameter(Position = 10, Mandatory = true, ValueFromPipeline = false, ParameterSetName = "SourceTemplate", HelpMessage = "XAML template XmlDocument")]
      [Alias("XamlTemplate")]
      public XmlDocument SourceTemplate { get; set; }

      [Parameter(Mandatory = false, ValueFromPipeline = false, HelpMessage = "Do not show in a popup Window (currently only works on PoshConsole)")]
      public SwitchParameter Inline { get; set; }

      // TELL ME ABOUT IT!!!
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Passthru")]
      [Parameter(Mandatory = false, HelpMessage = "Write out the window")]
      public SwitchParameter Passthru { get; set; }

      [Parameter(Mandatory = false, HelpMessage = "Export variables for the content of the window")]
      public SwitchParameter ExportNamedElements { get; set; }



      #region AUTOGENERATED PROPERTIES
      // ReSharper disable InconsistentNaming
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public SwitchParameter AllowDrop { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public SwitchParameter AllowsTransparency { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public SwitchParameter ClipToBounds { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public SwitchParameter Focusable { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public SwitchParameter ForceCursor { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public SwitchParameter IsEnabled { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public SwitchParameter IsHitTestVisible { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public SwitchParameter IsTabStop { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public SwitchParameter OverridesDefaultStyle { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public SwitchParameter ShowActivated { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public SwitchParameter ShowInTaskbar { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public SwitchParameter SnapsToDevicePixels { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public SwitchParameter Topmost { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public SwitchParameter DialogResult { get; set; }

      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public Nullable<System.Double> FontSize { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public Nullable<System.Double> Height { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public Nullable<System.Double> Left { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public Nullable<System.Double> MaxHeight { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public Nullable<System.Double> MaxWidth { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public Nullable<System.Double> MinHeight { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public Nullable<System.Double> MinWidth { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public Nullable<System.Double> Opacity { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public Nullable<System.Double> Top { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public Nullable<System.Double> Width { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public Nullable<System.Int32> TabIndex { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      //public Object Content { get; set; }
      //[Parameter(Mandatory = false, ValueFromPipeline = false)]
      public Object DataContext { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public Object Tag { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public Object ToolTip { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public String ContentStringFormat { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public String Name { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public String Title { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Uid"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public String Uid { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public ContextMenu ContextMenu { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public ControlTemplate Template { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public DataTemplateSelector ContentTemplateSelector { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Data.BindingGroup BindingGroup { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public DataTemplate ContentTemplate { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public FlowDirection? FlowDirection { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public FontStretch? FontStretch { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public FontStyle? FontStyle { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public FontWeight? FontWeight { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public HorizontalAlignment? HorizontalAlignment { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public HorizontalAlignment? HorizontalContentAlignment { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Input.CommandBinding[] CommandBindings { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Input.Cursor Cursor { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Input.InputBinding[] InputBindings { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Input.InputScope InputScope { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Markup.XmlLanguage Language { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Media.Brush Background { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Media.Brush BorderBrush { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Media.Brush Foreground { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Media.Brush OpacityMask { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Media.Effects.BitmapEffect BitmapEffect { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Media.Effects.BitmapEffectInput BitmapEffectInput { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Media.Effects.Effect Effect { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Media.FontFamily FontFamily { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Media.Geometry Clip { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Media.ImageSource Icon { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Media.Transform LayoutTransform { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Media.Transform RenderTransform { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public Point? RenderTransformOrigin { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public ResizeMode? ResizeMode { get; set; }
      // These collection things expect ARE read-only, EXCEPT that we accept them as parameters

      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public ResourceDictionary Resources { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Size? RenderSize { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public SizeToContent? SizeToContent { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public Style FocusVisualStyle { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public Style Style { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public Thickness? BorderThickness { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public Thickness? Margin { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public Thickness? Padding { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public TriggerCollection Triggers { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public VerticalAlignment? VerticalAlignment { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public VerticalAlignment? VerticalContentAlignment { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public Visibility? Visibility { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public IntPtr? Owner { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public Window OwnerWindow { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public WindowStartupLocation? WindowStartupLocation { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public WindowState? WindowState { get; set; }
      [Parameter(Mandatory = false, ValueFromPipeline = false)]
      public WindowStyle? WindowStyle { get; set; }
      #endregion AUTOGENERATED PROPERTIES
      #region AUTOGENERATED EVENTS
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.ComponentModel.CancelEventHandler On_Closing { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public EventHandler On_Activated { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public EventHandler On_Closed { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public EventHandler On_ContentRendered { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public EventHandler On_Deactivated { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public EventHandler On_Initialized { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public EventHandler On_LayoutUpdated { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public EventHandler On_LocationChanged { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public EventHandler On_SourceInitialized { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public EventHandler On_StateChanged { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public EventHandler<System.Windows.Data.DataTransferEventArgs> On_SourceUpdated { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public EventHandler<System.Windows.Data.DataTransferEventArgs> On_TargetUpdated { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public ContextMenuEventHandler On_ContextMenuClosing { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public ContextMenuEventHandler On_ContextMenuOpening { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public ToolTipEventHandler On_ToolTipClosing { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public ToolTipEventHandler On_ToolTipOpening { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public DependencyPropertyChangedEventHandler On_DataContextChanged { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public DependencyPropertyChangedEventHandler On_FocusableChanged { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public DependencyPropertyChangedEventHandler On_IsEnabledChanged { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public DependencyPropertyChangedEventHandler On_IsHitTestVisibleChanged { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public DependencyPropertyChangedEventHandler On_IsKeyboardFocusedChanged { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public DependencyPropertyChangedEventHandler On_IsKeyboardFocusWithinChanged { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public DependencyPropertyChangedEventHandler On_IsMouseCapturedChanged { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public DependencyPropertyChangedEventHandler On_IsMouseCaptureWithinChanged { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public DependencyPropertyChangedEventHandler On_IsMouseDirectlyOverChanged { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public DependencyPropertyChangedEventHandler On_IsStylusCapturedChanged { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public DependencyPropertyChangedEventHandler On_IsStylusCaptureWithinChanged { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public DependencyPropertyChangedEventHandler On_IsStylusDirectlyOverChanged { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public DependencyPropertyChangedEventHandler On_IsVisibleChanged { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public DragEventHandler On_DragEnter { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public DragEventHandler On_DragLeave { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public DragEventHandler On_DragOver { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public DragEventHandler On_Drop { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public DragEventHandler On_PreviewDragEnter { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public DragEventHandler On_PreviewDragLeave { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public DragEventHandler On_PreviewDragOver { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public DragEventHandler On_PreviewDrop { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public GiveFeedbackEventHandler On_GiveFeedback { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public GiveFeedbackEventHandler On_PreviewGiveFeedback { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Input.KeyboardFocusChangedEventHandler On_GotKeyboardFocus { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Input.KeyboardFocusChangedEventHandler On_LostKeyboardFocus { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Input.KeyboardFocusChangedEventHandler On_PreviewGotKeyboardFocus { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Input.KeyboardFocusChangedEventHandler On_PreviewLostKeyboardFocus { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Input.KeyEventHandler On_KeyDown { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Input.KeyEventHandler On_KeyUp { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Input.KeyEventHandler On_PreviewKeyDown { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Input.KeyEventHandler On_PreviewKeyUp { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Input.MouseButtonEventHandler On_MouseDoubleClick { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Input.MouseButtonEventHandler On_MouseDown { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Input.MouseButtonEventHandler On_MouseLeftButtonDown { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Input.MouseButtonEventHandler On_MouseLeftButtonUp { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Input.MouseButtonEventHandler On_MouseRightButtonDown { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Input.MouseButtonEventHandler On_MouseRightButtonUp { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Input.MouseButtonEventHandler On_MouseUp { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Input.MouseButtonEventHandler On_PreviewMouseDoubleClick { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Input.MouseButtonEventHandler On_PreviewMouseDown { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Input.MouseButtonEventHandler On_PreviewMouseLeftButtonDown { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Input.MouseButtonEventHandler On_PreviewMouseLeftButtonUp { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Input.MouseButtonEventHandler On_PreviewMouseRightButtonDown { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Input.MouseButtonEventHandler On_PreviewMouseRightButtonUp { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Input.MouseButtonEventHandler On_PreviewMouseUp { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Input.MouseEventHandler On_GotMouseCapture { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Input.MouseEventHandler On_LostMouseCapture { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Input.MouseEventHandler On_MouseEnter { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Input.MouseEventHandler On_MouseLeave { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Input.MouseEventHandler On_MouseMove { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Input.MouseEventHandler On_PreviewMouseMove { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Input.MouseWheelEventHandler On_MouseWheel { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Input.MouseWheelEventHandler On_PreviewMouseWheel { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Input.QueryCursorEventHandler On_QueryCursor { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Input.StylusButtonEventHandler On_PreviewStylusButtonDown { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Input.StylusButtonEventHandler On_PreviewStylusButtonUp { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Input.StylusButtonEventHandler On_StylusButtonDown { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Input.StylusButtonEventHandler On_StylusButtonUp { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Input.StylusDownEventHandler On_PreviewStylusDown { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Input.StylusDownEventHandler On_StylusDown { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Input.StylusEventHandler On_GotStylusCapture { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Input.StylusEventHandler On_LostStylusCapture { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Input.StylusEventHandler On_PreviewStylusInAirMove { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Input.StylusEventHandler On_PreviewStylusInRange { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Input.StylusEventHandler On_PreviewStylusMove { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Input.StylusEventHandler On_PreviewStylusOutOfRange { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Input.StylusEventHandler On_PreviewStylusUp { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Input.StylusEventHandler On_StylusEnter { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Input.StylusEventHandler On_StylusInAirMove { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Input.StylusEventHandler On_StylusInRange { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Input.StylusEventHandler On_StylusLeave { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Input.StylusEventHandler On_StylusMove { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Input.StylusEventHandler On_StylusOutOfRange { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Input.StylusEventHandler On_StylusUp { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Input.StylusSystemGestureEventHandler On_PreviewStylusSystemGesture { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Input.StylusSystemGestureEventHandler On_StylusSystemGesture { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Input.TextCompositionEventHandler On_PreviewTextInput { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public System.Windows.Input.TextCompositionEventHandler On_TextInput { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public QueryContinueDragEventHandler On_PreviewQueryContinueDrag { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public QueryContinueDragEventHandler On_QueryContinueDrag { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public RequestBringIntoViewEventHandler On_RequestBringIntoView { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public RoutedEventHandler On_GotFocus { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public RoutedEventHandler On_Loaded { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public RoutedEventHandler On_LostFocus { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public RoutedEventHandler On_Unloaded { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"), Parameter(Mandatory = false, ValueFromPipeline = false)]
      public SizeChangedEventHandler On_SizeChanged { get; set; }
      // ReSharper restore InconsistentNaming
      #endregion AUTOGENERATED EVENTS
      #endregion Parameters

      private static Window _window;
      private static Dispatcher _dispatcher;
      private static IPSWpfConsole _xamlUI;

      private bool _wantedAsync;

      private XmlDocument _template;
      //private FrameworkElement _element;
      private FrameworkElement _element;
      private ItemsControl _host;
      private WindowDispatcherAsyncResult _asyncResult;
      #region Methods


      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
      protected override void BeginProcessing()
      {
         base.BeginProcessing();
         TouchDefaults();
         RedefineWriteOutput();
         _wantedAsync = Async.ToBool();
         if (_window == null)
         {

            _template = GetXaml();

            if (!Owner.HasValue)
            {
               Owner = OwnerWindow != null ? new WindowInteropHelper(OwnerWindow).Handle : Process.GetCurrentProcess().MainWindowHandle;
            }

            // If they don't want a popup (or Async Threaded, which forces the issue)
            // AND if we're in a WPF host (so we can give them what they want)...
            if (Host.PrivateData != null && Host.PrivateData.BaseObject is IPSWpfOptions && Inline.ToBool() && !Async.ToBool())
            {
               //((IPSWpfHost)).GetWpfConsole();
               _xamlUI = ((IPSWpfOptions)Host.PrivateData.BaseObject).WpfConsole;
               //_window = _xamlUI.RootWindow;
               _dispatcher = _xamlUI.Dispatcher;
               _xamlUI.RootWindow.LoadTemplates();
            }
            // if they *want* it shown async ...
            // Or it MUST be shown Async (because we're not in a STA thread)
            else if (_wantedAsync || System.Threading.Thread.CurrentThread.GetApartmentState() != System.Threading.ApartmentState.STA)
            {
               Async = true;
               Inline = false;

               _asyncResult = Presentation.Start(_template, SetWindowParams, Owner);
               _window = _asyncResult.Window;
               _dispatcher = _asyncResult.Dispatcher;
            }
            // otherwise, 
            // they do not want the async thread, and we're in a STA host
            // so we'll just create the window and call ShowDialog() at the end...
            else
            {
               // Async = false; // this is already false
               Inline = false;
               _window = Presentation.NewWindow(_template, Owner);
               SetWindowParams(_window);
               _dispatcher = _window.Dispatcher;
            }

            // preload the template into _element ...
            if (_template != null)
            {
               ErrorRecord error = (ErrorRecord)_dispatcher.Invoke((Func<ErrorRecord>)(() =>
               {
                  ErrorRecord err = null;
                  if (_template.TryLoadXaml(out _element, out err))
                  {
                     // if the xaml template is a window, we will toss it unless we're in a WpfHost...
                     if (_element is Window)
                     {
                        //if (Host.PrivateData != null && Host.PrivateData.BaseObject is IPSWpfOptions)
                        //{
                        //   if(_window != null)
                        //   {
                        //      ShowUIWindowDictionary.Instance.Remove(_window);
                        //   }
                        //   _window = (Window)_element;
                        //   //_window.Show();
                        //   try
                        //   {
                        //      SetWindowParams(_window);
                        //   }
                        //   catch (Exception ex)
                        //   {
                        //      err = new ErrorRecord(ex, "Error Setting Parameter Property", ErrorCategory.InvalidArgument, Content);
                        //   }
                        //   _dispatcher = _window.Dispatcher;
                        //}
                        _element = null;
                     }
                     return err;
                  }
                  else
                  {
                     ContentElement conElement;
                     if (_template.TryLoadXaml(out conElement, out err))
                     {
                        DocumentOutput(conElement);
                     }
                     return err;
                  }
               }));
               if (error != null) { WriteError(error); }
            }


         }
         if (_window != null)
         {
            _window.Closed += (object sender, EventArgs e) =>
            {
               UIWindowDictionary.Instance.Remove((Window)sender);
               ((System.Collections.Hashtable)((PSObject)SessionState.PSVariable.GetValue("Global:ShowUI")).BaseObject)["ActiveWindow"] = null;
            };
         }
      }

      private void RedefineWriteOutput()
      {
         Invoke(InvokeCommand.NewScriptBlock(
@"$Global:UIOutput = @()
function Global:Write-UIOutput($inputObject) {
   BEGIN {
      if ($inputObject) {
         $Global:UIOutput += $inputObject
      }
   }
   PROCESS {
      if($_) {
         $Global:UIOutput += $_
      }
   }
}"));
      }

      // TODO: Consider undefining Write-UIOutput
      //private void UndefineWriteOutput()
      //{
      //   ScriptBlockBase.Invoke(InvokeCommand.NewScriptBlock(@"Remove-Item Function:\Write-UIOutput"));
      //}

      private void TouchDefaults()
      {
         // Default value for SizeToContent 
         if (SizeToContent == null)
         {

            if (Width == null && Height == null)
            {
               SizeToContent = System.Windows.SizeToContent.WidthAndHeight;
            }
            else if (Height == null)
            {
               SizeToContent = System.Windows.SizeToContent.Height;
            }
            else if (Width == null)
            {
               SizeToContent = System.Windows.SizeToContent.Width;
            }
         }
         // Default value for Title
         if (Title == null)
         {
            Title = "Show";
         }
      }

      // duh.....
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1505:AvoidUnmaintainableCode"),
       System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
      private void SetWindowParams(Window window)
      {
         UIWindowDictionary.Instance.Add(window);
         var showUI = SessionState.PSVariable.GetValue("Global:ShowUI");
         if (showUI == null) {
            var ht = new Hashtable();
            ht.Add("ActiveWindow", window);
            SessionState.PSVariable.Set( new PSVariable("Global:ShowUI", new PSObject(ht), ScopedItemOptions.ReadOnly));
         }
         else if (showUI is PSObject) {
            var ht = ((PSObject)showUI).BaseObject as Hashtable;
            ht["ActiveWindow"] = window;
         }
         else if (showUI is Hashtable) {
            ((Hashtable)showUI)["ActiveWindow"] = window;
         }
         // NOTE: We want to remove these once they're closed, but ... 
         // probably not right away, since they might contain data the user wants?
         // window.Closed += (sender, args) => ((List<Window>)windows.Value).Remove((Window)sender);

         #region AUTOGENERATED PROPERTY PARAMETER CODE
         if (AllowDrop.IsPresent)
         {
            window.AllowDrop = AllowDrop.ToBool();
         }
         if (AllowsTransparency.IsPresent)
         {
            window.AllowsTransparency = AllowsTransparency.ToBool();
         }
         if (ClipToBounds.IsPresent)
         {
            window.ClipToBounds = ClipToBounds.ToBool();
         }
         if (Focusable.IsPresent)
         {
            window.Focusable = Focusable.ToBool();
         }
         if (ForceCursor.IsPresent)
         {
            window.ForceCursor = ForceCursor.ToBool();
         }
         if (IsEnabled.IsPresent)
         {
            window.IsEnabled = IsEnabled.ToBool();
         }
         if (IsHitTestVisible.IsPresent)
         {
            window.IsHitTestVisible = IsHitTestVisible.ToBool();
         }
         if (IsTabStop.IsPresent)
         {
            window.IsTabStop = IsTabStop.ToBool();
         }
         if (OverridesDefaultStyle.IsPresent)
         {
            window.OverridesDefaultStyle = OverridesDefaultStyle.ToBool();
         }
         if (ShowActivated.IsPresent)
         {
            window.ShowActivated = ShowActivated.ToBool();
         }
         if (ShowInTaskbar.IsPresent)
         {
            window.ShowInTaskbar = ShowInTaskbar.ToBool();
         }
         if (SnapsToDevicePixels.IsPresent)
         {
            window.SnapsToDevicePixels = SnapsToDevicePixels.ToBool();
         }
         if (Topmost.IsPresent)
         {
            window.Topmost = Topmost.ToBool();
         }
         if (FontSize.HasValue)
         {
            window.FontSize = FontSize.Value;
         }
         if (Height.HasValue)
         {
            window.Height = Height.Value;
         }
         if (Left.HasValue)
         {
            window.Left = Left.Value;
         }
         if (MaxHeight.HasValue)
         {
            window.MaxHeight = MaxHeight.Value;
         }
         if (MaxWidth.HasValue)
         {
            window.MaxWidth = MaxWidth.Value;
         }
         if (MinHeight.HasValue)
         {
            window.MinHeight = MinHeight.Value;
         }
         if (MinWidth.HasValue)
         {
            window.MinWidth = MinWidth.Value;
         }
         if (Opacity.HasValue)
         {
            window.Opacity = Opacity.Value;
         }
         if (Top.HasValue)
         {
            window.Top = Top.Value;
         }
         if (Width.HasValue)
         {
            window.Width = Width.Value;
         }
         if (TabIndex.HasValue)
         {
            window.TabIndex = TabIndex.Value;
         }
         if (DialogResult.IsPresent)
         {
            window.DialogResult = DialogResult.ToBool();
         }
         //if (Content != null)
         //{
         //   window.Content = Content;
         //}
         if (DataContext != null)
         {
            window.DataContext = DataContext;
         }
         if (Tag != null)
         {
            window.Tag = Tag;
         }
         if (ToolTip != null)
         {
            window.ToolTip = ToolTip;
         }
         if (ContentStringFormat != null)
         {
            window.ContentStringFormat = ContentStringFormat;
         }
         if (Name != null)
         {
            window.Name = Name;
         }
         if (Title != null)
         {
            window.Title = Title;
         }
         if (Uid != null)
         {
            window.Uid = Uid;
         }
         if (ContextMenu != null)
         {
            window.ContextMenu = ContextMenu;
         }
         if (Template != null)
         {
            window.Template = Template;
         }
         if (ContentTemplateSelector != null)
         {
            window.ContentTemplateSelector = ContentTemplateSelector;
         }
         if (BindingGroup != null)
         {
            window.BindingGroup = BindingGroup;
         }
         if (ContentTemplate != null)
         {
            window.ContentTemplate = ContentTemplate;
         }
         if (FlowDirection.HasValue)
         {
            window.FlowDirection = FlowDirection.Value;
         }
         if (FontStretch.HasValue)
         {
            window.FontStretch = FontStretch.Value;
         }
         if (FontStyle.HasValue)
         {
            window.FontStyle = FontStyle.Value;
         }
         if (FontWeight.HasValue)
         {
            window.FontWeight = FontWeight.Value;
         }
         if (HorizontalAlignment.HasValue)
         {
            window.HorizontalAlignment = HorizontalAlignment.Value;
         }
         if (HorizontalContentAlignment.HasValue)
         {
            window.HorizontalContentAlignment = HorizontalContentAlignment.Value;
         }
         if (CommandBindings != null)
         {
            foreach (var val in CommandBindings)
            {
               window.CommandBindings.Add(val);
            }
         }
         if (Cursor != null)
         {
            window.Cursor = Cursor;
         }
         if (InputBindings != null)
         {
            foreach (var val in InputBindings)
            {
               window.InputBindings.Add(val);
            }
         }
         if (InputScope != null)
         {
            window.InputScope = InputScope;
         }
         if (Language != null)
         {
            window.Language = Language;
         }
         if (Background != null)
         {
            window.Background = Background;
         }
         if (BorderBrush != null)
         {
            window.BorderBrush = BorderBrush;
         }
         if (Foreground != null)
         {
            window.Foreground = Foreground;
         }
         if (OpacityMask != null)
         {
            window.OpacityMask = OpacityMask;
         }
         //if (BitmapEffect != null)
         //{
         //   window.BitmapEffect = BitmapEffect;
         //}
         //if (BitmapEffectInput != null)
         //{
         //   window.BitmapEffectInput = BitmapEffectInput;
         //}
         if (Effect != null)
         {
            window.Effect = Effect;
         }
         if (FontFamily != null)
         {
            window.FontFamily = FontFamily;
         }
         if (Clip != null)
         {
            window.Clip = Clip;
         }
         if (Icon != null)
         {
            window.Icon = Icon;
         }
         if (LayoutTransform != null)
         {
            window.LayoutTransform = LayoutTransform;
         }
         if (RenderTransform != null)
         {
            window.RenderTransform = RenderTransform;
         }
         if (RenderTransformOrigin.HasValue)
         {
            window.RenderTransformOrigin = RenderTransformOrigin.Value;
         }
         if (ResizeMode.HasValue)
         {
            window.ResizeMode = ResizeMode.Value;
         }
         if (Resources != null)
         {
            window.Resources = Resources;
         }
         if (RenderSize.HasValue)
         {
            window.RenderSize = RenderSize.Value;
         }
         if (SizeToContent.HasValue)
         {
            window.SizeToContent = SizeToContent.Value;
         }
         if (FocusVisualStyle != null)
         {
            window.FocusVisualStyle = FocusVisualStyle;
         }
         if (Style != null)
         {
            window.Style = Style;
         }
         if (BorderThickness.HasValue)
         {
            window.BorderThickness = BorderThickness.Value;
         }
         if (Margin.HasValue)
         {
            window.Margin = Margin.Value;
         }
         if (Padding.HasValue)
         {
            window.Padding = Padding.Value;
         }
         if (Triggers != null)
         {
            foreach (var val in Triggers)
            {
               window.Triggers.Add(val);
            }
         }
         if (VerticalAlignment.HasValue)
         {
            window.VerticalAlignment = VerticalAlignment.Value;
         }
         if (VerticalContentAlignment.HasValue)
         {
            window.VerticalContentAlignment = VerticalContentAlignment.Value;
         }
         if (Visibility.HasValue)
         {
            window.Visibility = Visibility.Value;
         }
         if (WindowStartupLocation.HasValue)
         {
            window.WindowStartupLocation = WindowStartupLocation.Value;
         }
         if (WindowState.HasValue)
         {
            window.WindowState = WindowState.Value;
         }
         if (WindowStyle.HasValue)
         {
            window.WindowStyle = WindowStyle.Value;
         }
         #endregion AUTOGENERATED PROPERTY PARAMETER CODE
         #region AUTOGENERATED EVENT PARAMETER CODE
         if (On_Closing != null)
         {
            window.Closing += On_Closing;
         }
         if (On_Activated != null)
         {
            window.Activated += On_Activated;
         }
         if (On_Closed != null)
         {
            window.Closed += On_Closed;
         }
         if (On_ContentRendered != null)
         {
            window.ContentRendered += On_ContentRendered;
         }
         if (On_Deactivated != null)
         {
            window.Deactivated += On_Deactivated;
         }
         if (On_Initialized != null)
         {
            window.Initialized += On_Initialized;
         }
         if (On_LayoutUpdated != null)
         {
            window.LayoutUpdated += On_LayoutUpdated;
         }
         if (On_LocationChanged != null)
         {
            window.LocationChanged += On_LocationChanged;
         }
         if (On_SourceInitialized != null)
         {
            window.SourceInitialized += On_SourceInitialized;
         }
         if (On_StateChanged != null)
         {
            window.StateChanged += On_StateChanged;
         }
         if (On_SourceUpdated != null)
         {
            window.SourceUpdated += On_SourceUpdated;
         }
         if (On_TargetUpdated != null)
         {
            window.TargetUpdated += On_TargetUpdated;
         }
         if (On_ContextMenuClosing != null)
         {
            window.ContextMenuClosing += On_ContextMenuClosing;
         }
         if (On_ContextMenuOpening != null)
         {
            window.ContextMenuOpening += On_ContextMenuOpening;
         }
         if (On_ToolTipClosing != null)
         {
            window.ToolTipClosing += On_ToolTipClosing;
         }
         if (On_ToolTipOpening != null)
         {
            window.ToolTipOpening += On_ToolTipOpening;
         }
         if (On_DataContextChanged != null)
         {
            window.DataContextChanged += On_DataContextChanged;
         }
         if (On_FocusableChanged != null)
         {
            window.FocusableChanged += On_FocusableChanged;
         }
         if (On_IsEnabledChanged != null)
         {
            window.IsEnabledChanged += On_IsEnabledChanged;
         }
         if (On_IsHitTestVisibleChanged != null)
         {
            window.IsHitTestVisibleChanged += On_IsHitTestVisibleChanged;
         }
         if (On_IsKeyboardFocusedChanged != null)
         {
            window.IsKeyboardFocusedChanged += On_IsKeyboardFocusedChanged;
         }
         if (On_IsKeyboardFocusWithinChanged != null)
         {
            window.IsKeyboardFocusWithinChanged += On_IsKeyboardFocusWithinChanged;
         }
         if (On_IsMouseCapturedChanged != null)
         {
            window.IsMouseCapturedChanged += On_IsMouseCapturedChanged;
         }
         if (On_IsMouseCaptureWithinChanged != null)
         {
            window.IsMouseCaptureWithinChanged += On_IsMouseCaptureWithinChanged;
         }
         if (On_IsMouseDirectlyOverChanged != null)
         {
            window.IsMouseDirectlyOverChanged += On_IsMouseDirectlyOverChanged;
         }
         if (On_IsStylusCapturedChanged != null)
         {
            window.IsStylusCapturedChanged += On_IsStylusCapturedChanged;
         }
         if (On_IsStylusCaptureWithinChanged != null)
         {
            window.IsStylusCaptureWithinChanged += On_IsStylusCaptureWithinChanged;
         }
         if (On_IsStylusDirectlyOverChanged != null)
         {
            window.IsStylusDirectlyOverChanged += On_IsStylusDirectlyOverChanged;
         }
         if (On_IsVisibleChanged != null)
         {
            window.IsVisibleChanged += On_IsVisibleChanged;
         }
         if (On_DragEnter != null)
         {
            window.DragEnter += On_DragEnter;
         }
         if (On_DragLeave != null)
         {
            window.DragLeave += On_DragLeave;
         }
         if (On_DragOver != null)
         {
            window.DragOver += On_DragOver;
         }
         if (On_Drop != null)
         {
            window.Drop += On_Drop;
         }
         if (On_PreviewDragEnter != null)
         {
            window.PreviewDragEnter += On_PreviewDragEnter;
         }
         if (On_PreviewDragLeave != null)
         {
            window.PreviewDragLeave += On_PreviewDragLeave;
         }
         if (On_PreviewDragOver != null)
         {
            window.PreviewDragOver += On_PreviewDragOver;
         }
         if (On_PreviewDrop != null)
         {
            window.PreviewDrop += On_PreviewDrop;
         }
         if (On_GiveFeedback != null)
         {
            window.GiveFeedback += On_GiveFeedback;
         }
         if (On_PreviewGiveFeedback != null)
         {
            window.PreviewGiveFeedback += On_PreviewGiveFeedback;
         }
         if (On_GotKeyboardFocus != null)
         {
            window.GotKeyboardFocus += On_GotKeyboardFocus;
         }
         if (On_LostKeyboardFocus != null)
         {
            window.LostKeyboardFocus += On_LostKeyboardFocus;
         }
         if (On_PreviewGotKeyboardFocus != null)
         {
            window.PreviewGotKeyboardFocus += On_PreviewGotKeyboardFocus;
         }
         if (On_PreviewLostKeyboardFocus != null)
         {
            window.PreviewLostKeyboardFocus += On_PreviewLostKeyboardFocus;
         }
         if (On_KeyDown != null)
         {
            window.KeyDown += On_KeyDown;
         }
         if (On_KeyUp != null)
         {
            window.KeyUp += On_KeyUp;
         }
         if (On_PreviewKeyDown != null)
         {
            window.PreviewKeyDown += On_PreviewKeyDown;
         }
         if (On_PreviewKeyUp != null)
         {
            window.PreviewKeyUp += On_PreviewKeyUp;
         }
         if (On_MouseDoubleClick != null)
         {
            window.MouseDoubleClick += On_MouseDoubleClick;
         }
         if (On_MouseDown != null)
         {
            window.MouseDown += On_MouseDown;
         }
         if (On_MouseLeftButtonDown != null)
         {
            window.MouseLeftButtonDown += On_MouseLeftButtonDown;
         }
         if (On_MouseLeftButtonUp != null)
         {
            window.MouseLeftButtonUp += On_MouseLeftButtonUp;
         }
         if (On_MouseRightButtonDown != null)
         {
            window.MouseRightButtonDown += On_MouseRightButtonDown;
         }
         if (On_MouseRightButtonUp != null)
         {
            window.MouseRightButtonUp += On_MouseRightButtonUp;
         }
         if (On_MouseUp != null)
         {
            window.MouseUp += On_MouseUp;
         }
         if (On_PreviewMouseDoubleClick != null)
         {
            window.PreviewMouseDoubleClick += On_PreviewMouseDoubleClick;
         }
         if (On_PreviewMouseDown != null)
         {
            window.PreviewMouseDown += On_PreviewMouseDown;
         }
         if (On_PreviewMouseLeftButtonDown != null)
         {
            window.PreviewMouseLeftButtonDown += On_PreviewMouseLeftButtonDown;
         }
         if (On_PreviewMouseLeftButtonUp != null)
         {
            window.PreviewMouseLeftButtonUp += On_PreviewMouseLeftButtonUp;
         }
         if (On_PreviewMouseRightButtonDown != null)
         {
            window.PreviewMouseRightButtonDown += On_PreviewMouseRightButtonDown;
         }
         if (On_PreviewMouseRightButtonUp != null)
         {
            window.PreviewMouseRightButtonUp += On_PreviewMouseRightButtonUp;
         }
         if (On_PreviewMouseUp != null)
         {
            window.PreviewMouseUp += On_PreviewMouseUp;
         }
         if (On_GotMouseCapture != null)
         {
            window.GotMouseCapture += On_GotMouseCapture;
         }
         if (On_LostMouseCapture != null)
         {
            window.LostMouseCapture += On_LostMouseCapture;
         }
         if (On_MouseEnter != null)
         {
            window.MouseEnter += On_MouseEnter;
         }
         if (On_MouseLeave != null)
         {
            window.MouseLeave += On_MouseLeave;
         }
         if (On_MouseMove != null)
         {
            window.MouseMove += On_MouseMove;
         }
         if (On_PreviewMouseMove != null)
         {
            window.PreviewMouseMove += On_PreviewMouseMove;
         }
         if (On_MouseWheel != null)
         {
            window.MouseWheel += On_MouseWheel;
         }
         if (On_PreviewMouseWheel != null)
         {
            window.PreviewMouseWheel += On_PreviewMouseWheel;
         }
         if (On_QueryCursor != null)
         {
            window.QueryCursor += On_QueryCursor;
         }
         if (On_PreviewStylusButtonDown != null)
         {
            window.PreviewStylusButtonDown += On_PreviewStylusButtonDown;
         }
         if (On_PreviewStylusButtonUp != null)
         {
            window.PreviewStylusButtonUp += On_PreviewStylusButtonUp;
         }
         if (On_StylusButtonDown != null)
         {
            window.StylusButtonDown += On_StylusButtonDown;
         }
         if (On_StylusButtonUp != null)
         {
            window.StylusButtonUp += On_StylusButtonUp;
         }
         if (On_PreviewStylusDown != null)
         {
            window.PreviewStylusDown += On_PreviewStylusDown;
         }
         if (On_StylusDown != null)
         {
            window.StylusDown += On_StylusDown;
         }
         if (On_GotStylusCapture != null)
         {
            window.GotStylusCapture += On_GotStylusCapture;
         }
         if (On_LostStylusCapture != null)
         {
            window.LostStylusCapture += On_LostStylusCapture;
         }
         if (On_PreviewStylusInAirMove != null)
         {
            window.PreviewStylusInAirMove += On_PreviewStylusInAirMove;
         }
         if (On_PreviewStylusInRange != null)
         {
            window.PreviewStylusInRange += On_PreviewStylusInRange;
         }
         if (On_PreviewStylusMove != null)
         {
            window.PreviewStylusMove += On_PreviewStylusMove;
         }
         if (On_PreviewStylusOutOfRange != null)
         {
            window.PreviewStylusOutOfRange += On_PreviewStylusOutOfRange;
         }
         if (On_PreviewStylusUp != null)
         {
            window.PreviewStylusUp += On_PreviewStylusUp;
         }
         if (On_StylusEnter != null)
         {
            window.StylusEnter += On_StylusEnter;
         }
         if (On_StylusInAirMove != null)
         {
            window.StylusInAirMove += On_StylusInAirMove;
         }
         if (On_StylusInRange != null)
         {
            window.StylusInRange += On_StylusInRange;
         }
         if (On_StylusLeave != null)
         {
            window.StylusLeave += On_StylusLeave;
         }
         if (On_StylusMove != null)
         {
            window.StylusMove += On_StylusMove;
         }
         if (On_StylusOutOfRange != null)
         {
            window.StylusOutOfRange += On_StylusOutOfRange;
         }
         if (On_StylusUp != null)
         {
            window.StylusUp += On_StylusUp;
         }
         if (On_PreviewStylusSystemGesture != null)
         {
            window.PreviewStylusSystemGesture += On_PreviewStylusSystemGesture;
         }
         if (On_StylusSystemGesture != null)
         {
            window.StylusSystemGesture += On_StylusSystemGesture;
         }
         if (On_PreviewTextInput != null)
         {
            window.PreviewTextInput += On_PreviewTextInput;
         }
         if (On_TextInput != null)
         {
            window.TextInput += On_TextInput;
         }
         if (On_PreviewQueryContinueDrag != null)
         {
            window.PreviewQueryContinueDrag += On_PreviewQueryContinueDrag;
         }
         if (On_QueryContinueDrag != null)
         {
            window.QueryContinueDrag += On_QueryContinueDrag;
         }
         if (On_RequestBringIntoView != null)
         {
            window.RequestBringIntoView += On_RequestBringIntoView;
         }
         if (On_GotFocus != null)
         {
            window.GotFocus += On_GotFocus;
         }
         if (On_Loaded != null)
         {
            window.Loaded += On_Loaded;
         }
         if (On_LostFocus != null)
         {
            window.LostFocus += On_LostFocus;
         }
         if (On_Unloaded != null)
         {
            window.Unloaded += On_Unloaded;
         }
         if (On_SizeChanged != null)
         {
            window.SizeChanged += On_SizeChanged;
         }
         #endregion AUTOGENERATED EVENT PARAMETER CODE
      }


      // private Huddled.WPF.Controls.Interfaces.IPSXamlConsole xamlUI;
      // private FlowDocument _document = null;


      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")]
      protected override void ProcessRecord()
      {
         try {
            List<ScriptBlock> scriptContent = new List<ScriptBlock>();

            if (Content != null) {
               scriptContent.AddRange(Content);
            }

            List<ErrorRecord> errors = new List<ErrorRecord>();
            //_dispatcher.Invoke((Action<Window>)((Window _w) =>
            _window.Dispatcher.Invoke((Action<Window>)((Window _w) => {
               try {
                  if (scriptContent.Count > 0) {
                     List<PSObject> scriptResults = new List<PSObject>();
                     var cmd = MyInvocation.MyCommand;

                     // BUGBUG: This is needed for v1: SessionState.PSVariable.Set("window",_window);
                     // don't need to do Window.GetWindow(window) when we're creating the window...
                     var window = new PSVariable[] { };
                     if (_w != null) {
                        window = new[] { new PSVariable("this", _w), new PSVariable("window", _w) };
                     }
                     foreach (var pso in scriptContent) {
                        scriptResults.AddRange(Invoke(pso, window, Parameters));
                     }

                     if (scriptResults.Count > 0) {
                        foreach (PSObject obj in scriptResults) {
                           object output = obj.BaseObject;

                           // If the output is something that goes in a document ....
                           // Then we need to ditch our NewItemsControl and use a FlowDocumentScrollViewer
                           if (output is Block || output is Inline) {
                              DocumentOutput(output);
                           } // for now, we're only going to create our items control if you have more than one output
                           else if (scriptResults.Count == 1 && _w != null) // && output is Panel 
                        {
                              // ReSharper disable PossibleNullReferenceException
                              _w.Content = output;
                              // ReSharper restore PossibleNullReferenceException
                           }
                           else {
                              if (_host == null) { _host = XamlHelper.NewItemsControl(); }
                              if (_w == null && _host.Parent == null) {
                                 _xamlUI.CurrentBlock.Inlines.Add(new InlineUIContainer(_host));
                              }
                              else if (_host.Items.Count == 0) {
                                 // TODO: use some template-based magic 
                                 // to FIND a predefined ItemsControl, 
                                 // or the place where they want the ItemsControl
                                 //_window.Content
                                 // ReSharper disable PossibleNullReferenceException
                                 _w.Content = _host;
                                 // ReSharper restore PossibleNullReferenceException
                              }

                              if (_element != null) {
                                 ErrorRecord err;
                                 FrameworkElement el;
                                 if (_template.TryLoadXaml(out el, out err)) {
                                    el.DataContext = output;
                                    _host.Items.Add(el);
                                 }
                                 else {
                                    _host.Items.Add(output);
                                 }
                              }
                              else {
                                 _host.Items.Add(output);
                              }
                           }
                        }
                     }
                     else if (_element != null) {
                        if (_window == null) {
                           _xamlUI.CurrentBlock.Inlines.Add(new InlineUIContainer(_element));
                        }
                        else {
                           _w.Content = _element;
                        }
                     }
                  }
                  else if (_element != null) {
                     if (_window == null) {
                        _xamlUI.CurrentBlock.Inlines.Add(new InlineUIContainer(_element));
                     }
                     else {
                        _w.Content = _element;
                     }
                  }
               }
               catch (Exception ex) {
                  errors.Add(new ErrorRecord(ex, "Error creating WPF Content", ErrorCategory.NotSpecified, Content));
               }
            }), _window);
            foreach (ErrorRecord err in errors) {
               WriteError(err);
            }

            if (Passthru.ToBool() && (_window != null)) {
               WriteObject(_window);
            }
         }
         catch (Exception ex) {
            WriteError(new ErrorRecord(ex, "Error creating WPF Content", ErrorCategory.NotSpecified, Content));
         }
      }

      private static void DocumentOutput(object output)
      {
         Paragraph par;
         FlowDocument doc;
         // if we're dong a XamlUI Popup window (or are not in XamlUI) ...
         if (_window != null)
         {
            par = new Paragraph();
            doc = new FlowDocument(par);
            if (_xamlUI != null)
            {
               par.Background = _xamlUI.CurrentBlock.Background;
               par.Foreground = _xamlUI.CurrentBlock.Foreground;
               doc.Background = _xamlUI.Document.Background;
               doc.Foreground = _xamlUI.Document.Foreground;
            }

            _window.Content = new FlowDocumentScrollViewer
            {
               Document = doc,
               Width = _window.Width,
               Height = _window.Height,
               Margin = new Thickness(0),
               Padding = new Thickness(0),
               IsToolBarVisible = true
            };
         }
         else
         {
            par = _xamlUI.CurrentBlock;
            doc = _xamlUI.Document;
         }

         Block blockput = output as Block;
         if (blockput != null)
         {
            doc.Blocks.InsertAfter(par, blockput);
         }
         else
         {
            par.Inlines.Add((Inline)output);
         }
      }


      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Not suppressing the exception, just moving it into an ErrorRecord for PowerShell")]
      protected override void EndProcessing()
      {
         if(ExportNamedElements.ToBool())
         {
            if (_window.Dispatcher != null && Dispatcher.CurrentDispatcher != _window.Dispatcher)
            {
               _window.Dispatcher.Invoke((Action)(() =>
                  _window.Loaded += (s, a) => ExportVisual(s as Visual, "global")
               ));
            } else {
               _window.Loaded += (s, a) => ExportVisual(s as Visual, "global");
            }
         }

         try
         {
            //if (Host.PrivateData.BaseObject is IPSWpfOptions && !Popup.ToBool() && !Async.ToBool())
            //else if (Async.ToBool() || System.Threading.Thread.CurrentThread.GetApartmentState() != System.Threading.ApartmentState.STA)
            if (!Async.ToBool() && !Inline.ToBool())
            {
               _window.ShowDialog();
            }

            // if they INTENDED it to be synchronous, simulate that for them :)
            if (!_wantedAsync)
            {
               if (_asyncResult != null)
               {
                  _asyncResult.AsyncWaitHandle.WaitOne();
               }
               WriteObject(GetVariableValue("Global:UIOutput", null), true);
            }
         }
         catch (Exception ex)
         {
            if (_window != null)
            {
               _window.Close();
            }
            WriteError(new ErrorRecord(ex, "Error displaying WPF Content", ErrorCategory.NotSpecified, Content));
         }
         finally
         {
            _window = null;
            _dispatcher = null;
            _xamlUI = null;
         }
         //UndefineWriteOutput();
         base.EndProcessing();
      }


      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "XamlTemplates"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "ShowUIPath")]
      private XmlDocument GetXaml()
      {
         XmlDocument document = null;
         switch (ParameterSetName)
         {
            case "FileTemplate":
               {
                  if (!FileTemplate.Exists)
                  {
                     #region roll 10 for a saving throw
                     // templates in the actual template path always win if you don't specify the full file name
                     string template = Path.Combine(ScriptBase, FileTemplate.Name);
                     if (File.Exists(template))
                     {
                        FileTemplate = new FileInfo(template);
                     }
                     else
                     {  // but if there isn't one there, we'll consider the local path
                        template = Path.Combine(CurrentProviderLocation("FileSystem").Path, FileTemplate.Name);
                        if (File.Exists(template))
                        {
                           document = new XmlDocument();
                           document.Load(template);
                        }
                        else
                        {
                           throw new FileNotFoundException("Can't find the template file.  We searched the default $ShowUI.InstallLocation\\XamlTemplates folder, and the current path.", template);
                        }
                     }
                     #endregion saving throw
                  }
                  else
                  {
                     document = new XmlDocument();
                     document.Load(FileTemplate.FullName);
                  }
               }
               break;
            case "SourceTemplate":
               {
                  document = SourceTemplate;
               }
               break;
            case "DataTemplate":
               {

               } break;
            default:
               {
                  throw new InvalidOperationException("Bad Parameter Set");
               }
         }
         return document;
      }
      #endregion

   }
}
